package net.rayherring;

import java.sql.ResultSet;
import java.util.logging.Logger;

import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.event.player.PlayerChangedWorldEvent;
import org.bukkit.event.player.PlayerJoinEvent;

public class MyOnlPlayerListener implements Listener {
	
	Logger log = Logger.getLogger("Minecraft");
	OnlinePlayersSQL plugin;
	ResultSet result;
	
	public MyOnlPlayerListener(OnlinePlayersSQL plugin) {
		this.plugin = plugin;
		plugin.getServer().getPluginManager().registerEvents(this, plugin);
	}
	
	@EventHandler(priority = EventPriority.NORMAL)
	public void onPlayerJoin(PlayerJoinEvent event) {
		if (plugin.opConfig.isShowDebug()) {
			log.info("Player World Join: " + event.getPlayer().getName() + " " + event.getPlayer().getWorld().getName());
		}
		
		plugin.updatePlayerRecord(event.getPlayer());
	}
	
	@EventHandler(priority = EventPriority.NORMAL)
	public void onPlayerWorldChange(PlayerChangedWorldEvent event) {
		if ( plugin.opConfig.isShowDebug()) {
			log.info("Player World " + event.getPlayer().getName() + " " + event.getPlayer().getWorld().getName());
		}
		
		plugin.opSql.SqlQuery("UPDATE " + plugin.opConfig.getMySQLTable() + " SET " +
				"previous_world='" + event.getFrom().getName() + "', " +
				"current_world='" + event.getPlayer().getWorld().getName() + "' " +
				"WHERE player='" + event.getPlayer().getName() + "';" );
	}
	
	@EventHandler(priority = EventPriority.NORMAL)
	public void onPlayerDisconnect(PlayerQuitEvent event) {
		if ( plugin.opConfig.isShowDebug()) {
			log.info("Player Disconnected " + event.getPlayer().getName() + ".");
		}
		
		plugin.opSql.SqlQuery("UPDATE " + plugin.opConfig.getMySQLTable() + " SET online = false WHERE player='" + event.getPlayer().getName() + "'");
	}
}
